const jwt = require('jsonwebtoken');

function verify (token) {
    return new Promise((resolve, reject) => {
        jwt.verify(token, 'dyyao', (err, decode) => {
            if(err){
                resolve(false)
            } else {
                resolve(decode)
            }
        })
    })
}

async function auth (req, res, next) {
    try {
        const {token} = req.headers||req.body||req.query;
        const user = await verify(token);
        if(user) {
            req.user = user.data;
            next();
        } else {
            res.json({
                code: 401,
                msg: '登录状态已失效, 请重新登录'
            })
        }
    } catch(err) {
        next(err)
    }
}

function sign (data,iat) {
    iat = iat || Math.floor(Date.now() / 1000) + 60*60*2;
    return jwt.sign({ data, iat }, 'dyyao');
}

module.exports = {
    auth,
    verify,
    sign
}
